import { deleteText } from '../config/geoserver';
import { useMessage, useMessageBox } from './message';
export interface BasicAvueTableProps {
	// 新增修改form对象
	form?: any;
	// 是否在创建页面时即调用数据列表接口，默认为true
	createdIsNeed?: boolean;
	// 查询条件表单对象，类型为any
	queryForm?: any;
	// 数据列表数组
	dataTable?: any[];
	// 分页属性对象
	pagination?: AvuePages;
	//table loading状态，默认false
	loading?: boolean;
	// 数据列表查询接口api方法，接收任意数量参数，返回Promise
	pageList?: (...arg: any) => Promise<any>;
	// 数据删除接口
	deleteMethod?: (...arg: any) => Promise<any>;
	// props属性对象，类型为any
	props?: any;
	// 搜索表单数据格式调整
	searchFormFormatter?: (form: object) => object;
	// 获取表格成功回调
	getListSuccessCb?: (res: { records?: Array<Object>; [key: string]: any } | Array<any>) => void;
	// 当前操作行数据
	curItem?: object;
	// 弹窗开关控制
	dialogVisible?: { [key: string]: boolean };
	// 删除提示文案
	deleteText?: string;
}

export interface AvuePages {
	// 当前页码，默认为1
	currentPage?: number;
	// 每页显示条数，默认为20
	pageSize?: number;
	// 总条数，默认为0
	total?: number;
	// 每页显示条数选择器的选项数组，默认为[10,20,30,40,50]
	pageSizes?: any[];
	// 分页组件布局方式，可选值有 total,sizes,prev,jump,next，默认为'total, sizes, prev, pager, next, jumper'
	layout?: string;
	// 按钮显示背景色 默认显示
	background?: boolean;
	// 按钮显示个数 默认7个
	pagerCount?: number;
}

export function useAvueTable(options?: BasicAvueTableProps) {
	const defaultOptions: BasicAvueTableProps = {
		form: {},
		createdIsNeed: true,
		queryForm: {},
		dataTable: [],
		pagination: {
			currentPage: 1,
			pageSize: 20,
			total: 0,
			pageSizes: [10, 20, 30, 40, 50],
			layout: 'total, sizes, prev, pager, next, jumper',
			pagerCount: 7,
		} as AvuePages,
		loading: false,
		// props属性配置对象，用于自定义数据属性，默认值为 {item:'records',totalCount:'total'}
		props: {
			item: 'records',
			totalCount: 'total',
		},
		curItem: undefined,
		deleteText,
	};
	/**
	 * 合并默认属性配置和自定义属性配置
	 * @param options 默认属性配置对象
	 * @param props 自定义属性配置对象
	 * @returns 合并后的属性配置对象
	 */
	const mergeDefaultOptions = (options: any, props: any): BasicAvueTableProps => {
		for (const key in options) {
			if (!Object.getOwnPropertyDescriptor(props, key)) {
				props[key] = options[key];
			}
		}
		return props;
	};
	//覆盖默认值
	const state = mergeDefaultOptions(defaultOptions, options);
	/**
	 * 获取table数据
	 */
	const getList = async () => {
		if (state.pageList) {
			try {
				state.loading = true;
				const res = await state.pageList({
					...(state.searchFormFormatter ? state.searchFormFormatter(state.queryForm) : state.queryForm),
					current: state.pagination?.currentPage,
					size: state.pagination?.pageSize,
				});
				state.dataTable = res.data[state.props.item];
				state.pagination!.total = res.data[state.props.totalCount];
				state.getListSuccessCb && state.getListSuccessCb(res.data as any);
			} catch (err: any) {
				// useMessage().error(err.msg || err.data.msg);
			} finally {
				state.loading = false;
			}
		}
	};
	/**
	 * 每页数量变更处理事件
	 * @param val
	 */
	const sizeChange = (val: number) => {
		state.pagination!.pageSize = val;
		getList();
	};
	/**
	 * 翻页处理事件
	 * @param val
	 */
	const currentChange = (val: number) => {
		state.pagination!.currentPage = val;
		// getList();
	};
	/**
	 * 刷新table
	 */
	const refreshTable = () => {
		state.pagination!.currentPage = 1;
		getList();
	};
	/**
	 * 搜索事件
	 * @param form
	 * @param done
	 */
	const searchChange = (form: any, done: () => void) => {
		state.queryForm = form;
		state.pagination!.currentPage = 1;
		getList();
		done();
	};
	/**
	 *打开弹窗
	 * @param key 弹窗key
	 * @param row 当前选中行数据
	 */
	const handleOpenDialog = (key: string, row?: object) => {
		state.curItem = row;
		state.dialogVisible![key] = true;
	};
	/**
	 * 删除行数据
	 * @param id
	 * @returns
	 */
	const deleteRow = async (id: string) => {
		try {
			await useMessageBox().confirm(state.deleteText);
		} catch {
			return;
		}
		try {
			if (state.deleteMethod) {
				await state.deleteMethod(id);
				useMessage().success('删除成功');
				setTimeout(() => {
					getList();
				}, 100);
			}
		} catch (err: any) {
			// useMessage().error(err.msg || err.data.msg);
		}
	};

	return {
		refreshTable,
		getList,
		sizeChange,
		currentChange,
		searchChange,
		deleteRow,
		handleOpenDialog,
	};
}
